import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogOut, reqRegister } from '@/api/user'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import {
  LoginFormData,
  LoginResponseData,
  userInfoResponseData,
  RegisterFormData,
  ResponseData,
} from '@/api/user/type'
import type { UserState } from './types/types'
import { constantRoute, asnycRoute, anyRoute } from '@/router/routes'
import router from '@/router'

// 引入深拷贝方法
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'
// 过滤当前用户需要提示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
let dynamicRoutes = []
// 创建大仓库
let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户的唯一标识
      menuRouters: constantRoute, //仓库存储生成菜单需要的路由
      userName: '',
      avatar: '',
      jobNumber: '',
      buttons: [],
    }
  },
  // 异步和逻辑
  actions: {
    async userLogin(data: LoginFormData) {
      let result: userInfoResponseData = await reqLogin(data)
      console.log(result)
      if (result.code == 200) {
        this.token = result.data.token as string
        SET_TOKEN(result.data.token as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userInfo() {
      //   获取用户信息存储仓库
      let result: userInfoResponseData = await reqUserInfo()
      console.log('用户信息')
      console.log(result.data)
      if (result.code == 200) {
        this.userName = result.data.userName
        this.avatar = result.data.avatar
        this.jobNumber = result.data.jobNumber
        this.buttons = result.data.permissionValueList
        // // 计算当前用户需要展示的异步路由
        let userAsyncRoute = filterAsyncRoute(
          cloneDeep(asnycRoute),
          result.data.routerList,
        )
        this.menuRouters = [...constantRoute, ...userAsyncRoute, ...anyRoute]
        //动态增加异步路由
        ;[...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        console.log(router.getRoutes())

        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    // 退出登录
    async userLogout() {
      let result: any = await reqLogOut()
      if (result.code == 200) {
        this.userName = ''
        this.avatar = ''
        this.token = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userRegister(data: RegisterFormData) {
      let result: any = await reqRegister(data)
      console.log(result)

      if (result.code == 200) {
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
// 对外暴露：入口文件需要安装仓库
export default useUserStore
